//
//  RSACrypto.m
//  HHNMobileFramework
//
//  Created by huhmf on 15/7/9.
//  Copyright (c) 2015年 huihu. All rights reserved.
//

#import "RSACrypto.h"
#import <openssl/rsa.h>
#import <openssl/pem.h>

@implementation RSACrypto
{
    RSA *_rsa;
}

- (instancetype)initWithPublicKeyPath:(NSString *)keyPath {
    RSA *p_rsa = NULL;
    FILE *file = NULL;
    
    do {
        if ((file = fopen(keyPath.UTF8String, "r")) == NULL) {
            //[Logger error:TBase message:@"Open key file error."];
            break;
        }
        
        if ((p_rsa = PEM_read_RSA_PUBKEY(file, NULL, NULL, NULL)) == NULL) {
            //[Logger error:TBase message:@"Read public key file error."];
            break;
        }
    } while (0);
    
    if (file) {
        fclose(file);
    }
    
    if (!p_rsa) {
        return nil;
    }
    
    self = [super init];
    if (self) {
        _rsa = p_rsa;
    }
    return self;
}

- (void)dealloc
{
    if (_rsa) {
        RSA_free(_rsa);
    }
}

- (NSData *)encryptDataWithPublicKey:(NSData *)plainData
{
    if (plainData == nil) {
        return nil;
    }
    
    int rsaLength = RSA_size(_rsa);
    unsigned char *encryptedData = (unsigned char *)malloc(rsaLength + 1);
    memset(encryptedData, 0, rsaLength + 1);
    
    // rsa encrypt via openssl
    int ret = RSA_public_encrypt((int)plainData.length,
                                 (unsigned char *)plainData.bytes,
                                 encryptedData,
                                 _rsa,
                                 RSA_PKCS1_PADDING);
    if (ret < 0)
    {
        free(encryptedData);
        return nil;
    }
    
    NSData *result = [NSData dataWithBytes:encryptedData length:ret];
    
    free(encryptedData);
    return result;
}

@end
